package main

import (
	"encoding/json"
	"fmt"
	"github.com/lionsoul2014/ip2region/binding/golang/xdb"
	"io/ioutil"
	"log"
	"net/http"
	"time"
)

// 定义一个结构体来匹配 JSON 数据的结构
type Response struct {
	Origin string `json:"origin"`
}

func main() {
	var dbPath = "./ip2region.xdb"
	print("asa")
	searcher, err := xdb.NewWithFileOnly(dbPath)
	if err != nil {
		fmt.Printf("failed to create searcher: %s\n", err.Error())
		return
	}

	defer searcher.Close()

	// do the search
	ip := getIPV4()
	fmt.Printf("Ipv4：%s\n", ip)
	fmt.Printf("Ipv6：%s\n", getIPV6())
	var tStart = time.Now()
	region, err := searcher.SearchByStr(ip)
	if err != nil {
		fmt.Printf("failed to SearchIP(%s): %s\n", ip, err)
		return
	}

	fmt.Printf("{region: %s, took: %s}\n", region, time.Since(tStart))

}

func getIPV4() string {
	resp, err := http.Get("http://httpbin.org/ip")
	if err != nil {
		return ""
	}
	defer resp.Body.Close()
	var response Response
	err = json.NewDecoder(resp.Body).Decode(&response)
	if err != nil {
		log.Fatalf("Error decoding JSON: %v", err)
	}
	fmt.Println(response.Origin)
	return response.Origin
}

func getIPV6() string {
	resp, err := http.Get("https://ipv6.netarm.com")
	if err != nil {
		return ""
	}
	defer resp.Body.Close()
	content, _ := ioutil.ReadAll(resp.Body)
	return string(content)
}
